package com.glorysoft.sunnypda.ui.reportrepair

import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.glorysoft.sunnypda.BR
import com.glorysoft.sunnypda.R
import com.glorysoft.sunnypda.base.BaseActivity
import com.glorysoft.sunnypda.databinding.ActivityReportRepairInfoBinding
import com.glorysoft.sunnypda.entity.GetUsersEntity
import com.glorysoft.sunnypda.entity.ui.ToastMessageBean
import com.glorysoft.sunnypda.utils.PopWindowsUtils
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils
import kotlinx.android.synthetic.main.activity_report_repair_info.*
import org.apache.commons.lang3.StringUtils
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
import kotlin.collections.ArrayList

/**
 * FileName: ReportRepairInfoActivity
 * Author: XJH
 * Date: 2022/1/7 16:25
 * Description:
 * History:
 */
class ReportRepairInfoActivity : BaseActivity<ReportRepairInfoViewModel,ActivityReportRepairInfoBinding>(),
    View.OnClickListener {

    private var priorityPop: PopWindowsUtils.GeneralPop? = null
    private var userPop: PopWindowsUtils.GeneralPop? = null
    private var typePop: PopWindowsUtils.GeneralPop? = null
    var mDatePicker: CustomDatePicker? = null
    var mRFPID = ""
    var time: String? = null
    var userAdapter: UserListAdapter? = null
    var userList = ArrayList<String>()
    var usersEntityList = ArrayList<GetUsersEntity>()
    var editString = ""
    var handler = Handler()
    val delayRun = Runnable() {
        kotlin.run {
            val userList = userList(editString, usersEntityList)
            if (userPop == null) {
                userPop = PopWindowsUtils.getOneChoosePop(
                    this@ReportRepairInfoActivity,
                    flUserList.width,
                    userList,
                    ivUserArrow,
                    object :
                        PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(codeS: String, potion: Int) {
                            etUser.setText(codeS)
                            if (!userAdapter!!.data.contains(codeS)) {
                                userAdapter!!.addData(codeS)
                            }
                        }
                    })
            }
            if (userPop!!.isShowing) {
                userPop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivUserArrow)
                userPop?.showAsDropDown(flUserList, 0, 0)
            }
            PopWindowsUtils.popListAdapter!!.notifyDataSetChanged()
        }
    }

    override fun layoutId(): Int {
        return R.layout.activity_report_repair_info
    }

    override fun initVariableId(): Int {
        return BR.reportRepairInfoViewModel
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle("故障维修登记")
        mRFPID = intent.getStringExtra("RFPID")
        viewModel.getRepairInfo(mRFPID)
        viewModel.getUserInfo()

//        rbNormal.setOnClickListener(this)
//        rbEqp.setOnClickListener(this)
//        rbProgram.setOnClickListener(this)
        flPriorityList.setOnClickListener(this)
        flTypeList.setOnClickListener(this)
        ivUserArrow.setOnClickListener(this)
        cbPin.setOnClickListener(this)
        tvStartRepair.setOnClickListener(this)
        tvEndRepair.setOnClickListener(this)
        flTimeList.setOnClickListener(this)
        userAdapter = UserListAdapter(null)
        userAdapter!!.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        userAdapter!!.isFirstOnly(true)
        rvUserList.adapter = userAdapter
        initDatePicker()
    }

    override fun initData() {
        viewModel.defUI.callObserve.observe(this) {
            when (it.type) {
                0 -> {
//                    when (viewModel.repaidInfoEntity.RFR_TYPE) {
//                        "0" -> rbNormal.isChecked = true
//                        "1" -> rbEqp.isChecked = true
//                        "2" -> rbProgram.isChecked = true
//                    }
                    viewModel.repaidInfoEntity.RepairType = if(viewModel.repaidInfoEntity.RFR_TYPE == null)"" else viewModel.repaidInfoEntity.RFR_TYPE
                    cbPin.isChecked = viewModel.repaidInfoEntity.ISQUALITY == "1"
                    tvEndRepair.background =
                        resources.getDrawable(R.drawable.free_ui_blue_sky_selector_kuang_button_click_background)
                    tvEndRepair.isEnabled = true
                    tvStartRepair.background =
                        resources.getDrawable(R.drawable.free_ui_blue_sky_selector_kuang_button_click_background)
                    tvStartRepair.isEnabled = true
                    when (viewModel.repaidInfoEntity.RFR_CURR_STATE) {
                        0 -> {
                            tvEndRepair.setBackgroundColor(resources.getColor(R.color.select_gray))
                            tvEndRepair.isEnabled = false
                        }
                        1 -> {
                            llPin1.visibility = View.GONE
                            tvStartRepair.setBackgroundColor(resources.getColor(R.color.select_gray))
                            tvStartRepair.isEnabled = false
                        }
                        2 -> {
                            llPin1.visibility = View.GONE
                            tvEndRepair.setBackgroundColor(resources.getColor(R.color.select_gray))
                            tvEndRepair.isEnabled = false
                            tvStartRepair.setBackgroundColor(resources.getColor(R.color.select_gray))
                            tvStartRepair.isEnabled = false
                        }
                    }

                    mBinding.setVariable(BR.reportRepairInfoViewModel, viewModel)
                }
                1 -> {
                    val userListInfo = it.item as ArrayList<GetUsersEntity>
                    usersEntityList.addAll(userListInfo)
                }
            }

        }

        viewModel.defUI.startActivity.observe(this) {
            viewModel.defUI.toastEvent.value = ToastMessageBean("操作成功", true)
            setResult(RESULT_OK)
            viewModel.getRepairInfo(mRFPID)
        }

        etUser.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
            override fun afterTextChanged(s: Editable?) {
                if(delayRun!=null){
                    handler.removeCallbacks(delayRun);
                }
                editString = s.toString();
                handler.postDelayed(delayRun, 800);
            }

        })
    }

    override fun onClick(v: View?) {
        when (v?.id) {
//            R.id.rbNormal -> viewModel.repaidInfoEntity.RFR_TYPE = "0"
//            R.id.rbEqp -> viewModel.repaidInfoEntity.RFR_TYPE = "1"
//            R.id.rbProgram -> viewModel.repaidInfoEntity.RFR_TYPE = "2"
            R.id.cbPin -> {
                viewModel.repaidInfoEntity.ISQUALITY = if (cbPin.isChecked) "1" else "0"
                if (cbPin.isChecked) {
                    llPin2.visibility = View.VISIBLE
                } else {
                    llPin2.visibility = View.GONE
                }
            }
            R.id.flPriorityList -> {
                if (priorityPop == null) {
                    priorityPop = PopWindowsUtils.getOneChoosePop(
                        this,
                        flPriorityList.width,
                        viewModel.priorityList,
                        ivPriorityArrow,
                        object :
                            PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(codeS: String, potion: Int) {
                                tvPriority.text = codeS
                                viewModel.repaidInfoEntity.PRIORITY = codeS
                            }

                        })

                }

                if (priorityPop!!.isShowing) {
                    priorityPop?.dismiss()
                } else {
                    PopWindowsUtils.setArrowShow(ivPriorityArrow)
                    priorityPop?.showAsDropDown(flPriorityList, 0, 0)
                }
            }
            R.id.flTypeList -> {
                if (typePop == null) {
                    typePop = PopWindowsUtils.getOneChoosePop(
                        this,
                        flTypeList.width,
                        viewModel.typeList,
                        ivTypeArrow,
                        object :
                            PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(codeS: String, potion: Int) {
                                tvType.text = codeS
                                viewModel.repaidInfoEntity.RFR_TYPE = codeS
                            }
                        })

                }

                if (typePop!!.isShowing) {
                    typePop?.dismiss()
                } else {
                    PopWindowsUtils.setArrowShow(ivTypeArrow)
                    typePop?.showAsDropDown(flTypeList, 0, 0)
                }
            }
            R.id.ivUserArrow -> {
                val userList = userList(etUser.text.toString(), usersEntityList)
                if (userPop == null) {
                    userPop = PopWindowsUtils.getOneChoosePop(
                        this,
                        flUserList.width,
                        userList,
                        ivUserArrow,
                        object :
                            PopWindowsUtils.PopTextAndPositionCallback {
                            override fun onSuccess(codeS: String, potion: Int) {
                                etUser.setText(codeS)
                                if (!userAdapter!!.data.contains(codeS)) {
                                    userAdapter!!.addData(codeS)
                                }
                            }

                        })
                }
                if (userPop!!.isShowing) {
                    userPop?.dismiss()
                } else {
                    PopWindowsUtils.setArrowShow(ivUserArrow)
                    userPop?.showAsDropDown(flUserList, 0, 0)
                }
            }
            R.id.flTimeList -> {
                mDatePicker!!.show(System.currentTimeMillis())
            }
            R.id.tvStartRepair -> {
                userAdapter!!.data.forEach {
                    val split = it.split(":")
                    userList.add(split[1])
                }
                viewModel.changeRepairStatus(
                    1,
                    StringUtils.join(userList.toArray(), ";"),
                    tvTime.text.toString(),
                    etRemark.text.toString()
                )
            }
            R.id.tvEndRepair -> {
                viewModel.changeRepairStatus(2, "", "", "")
            }
        }
    }

    private fun initDatePicker() {
        val date = Date()
        val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm")

        val beginTimestamp = FreeApi_DateUtils.str2Long(dateFormat.format(date), true)
        val endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22 00:00", true)

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = CustomDatePicker(this, { timestamp ->
            time = FreeApi_DateUtils.long2Str(timestamp, true)
            tvTime.setText(time)
        }, beginTimestamp, endTimestamp)
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker!!.setCancelable(true)
        // 不显示时和分
        mDatePicker!!.setCanShowPreciseTime(true)
        // 不允许循环滚动
        mDatePicker!!.setScrollLoop(false)
        // 不允许滚动动画
        mDatePicker!!.setCanShowAnim(false)
    }

    fun userList(name: String, list: ArrayList<GetUsersEntity>): ArrayList<String> {
        viewModel.userList.clear()
        val pattern = Pattern.compile(name,Pattern.CASE_INSENSITIVE)

        list.forEach {
            val nameMatcher = pattern.matcher((it.name).toString())
            val noMatcher = pattern.matcher((it.worK_NO).toString())
            if (nameMatcher.find() || noMatcher.find()){
                viewModel.userList.add(it.name + ":" + it.worK_NO)
            }
        }

        return viewModel.userList
    }

}